package icu.cqcai.xinsi.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 扣子工作流服务 - 用于职位搜索
 */
@Service
public class CozeWorkflowService {

    private static final Logger logger = LoggerFactory.getLogger(CozeWorkflowService.class);

    // 扣子工作流配置
    private static final String COZE_WORKFLOW_API_URL = "https://api.coze.cn/v1/workflow/run";
    private static final String ACCESS_TOKEN = "pat_SwmNZRUPekSdjR31xF4jXMlc6tAV4k50Hiy6dZIsJLVmgK7VUk2gfsKWRTEbDO49";
    private static final String SPACE_ID = "7514500344975212563";
    private static final String WORKFLOW_ID = "7515262165143683087";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 搜索职位
     */
    public List<Map<String, Object>> searchJobs(JobSearchRequest request) {
        try {
            logger.info("开始调用扣子工作流搜索职位: {}", request);

            // 构建请求参数
            Map<String, Object> workflowRequest = buildWorkflowRequest(request);
            
            // 调用扣子工作流API
            String response = callCozeWorkflow(workflowRequest);
            
            // 解析响应
            List<Map<String, Object>> jobs = parseWorkflowResponse(response);
            
            logger.info("成功获取到 {} 个职位", jobs.size());
            return jobs;

        } catch (Exception e) {
            logger.error("调用扣子工作流失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 构建工作流请求参数
     */
    private Map<String, Object> buildWorkflowRequest(JobSearchRequest request) {
        Map<String, Object> parameters = new HashMap<>();
        
        // 必填参数
        parameters.put("jobName", request.getJobName());
        parameters.put("city", request.getCity());
        parameters.put("workExperience", request.getWorkExperience());
        parameters.put("education", request.getEducation());
        
        // 可选参数
        if (request.getSalaryMin() != null) {
            parameters.put("salaryMin", request.getSalaryMin());
        }
        if (request.getCompanyName() != null && !request.getCompanyName().trim().isEmpty()) {
            parameters.put("companyName", request.getCompanyName());
        }
        if (request.getCompanyType() != null) {
            parameters.put("companyType", request.getCompanyType());
        }

        Map<String, Object> workflowRequest = new HashMap<>();
        workflowRequest.put("workflow_id", WORKFLOW_ID);
        workflowRequest.put("parameters", parameters);
        workflowRequest.put("bot_id", "7515261380430266408"); // 添加bot_id

        logger.debug("工作流请求参数: {}", workflowRequest);
        return workflowRequest;
    }

    /**
     * 调用扣子工作流API
     */
    private String callCozeWorkflow(Map<String, Object> request) {
        try {
            logger.info("准备调用扣子工作流API: {}", COZE_WORKFLOW_API_URL);
            logger.debug("请求体: {}", request);
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(ACCESS_TOKEN);
            headers.set("User-Agent", "xinsi-job-search/1.0");

            logger.debug("请求头: {}", headers);

            // 创建请求实体
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                COZE_WORKFLOW_API_URL, entity, String.class);

            logger.info("API响应状态码: {}", response.getStatusCode());
            logger.debug("API响应头: {}", response.getHeaders());
            
            String responseBody = response.getBody();
            logger.debug("API响应体长度: {}", responseBody != null ? responseBody.length() : 0);
            
            if (response.getStatusCode() == HttpStatus.OK) {
                return responseBody;
            } else {
                logger.error("工作流API调用失败，状态码: {}, 响应体: {}", response.getStatusCode(), responseBody);
                throw new RuntimeException("工作流API调用失败，状态码: " + response.getStatusCode());
            }

        } catch (Exception e) {
            logger.error("调用扣子工作流API异常", e);
            throw new RuntimeException("工作流API调用异常: " + e.getMessage(), e);
        }
    }

    /**
     * 解析工作流响应
     */
    private List<Map<String, Object>> parseWorkflowResponse(String response) {
        try {
            List<Map<String, Object>> jobs = new ArrayList<>();
            
            logger.debug("原始响应内容: {}", response);
            
            // 首先尝试解析为完整的JSON响应（非流式）
            try {
                JsonNode rootNode = objectMapper.readTree(response);
                logger.debug("解析的根JSON节点: {}", rootNode);
                
                // 检查是否有data字段
                if (rootNode.has("data")) {
                    JsonNode dataNode = rootNode.get("data");
                    
                    // 如果data是字符串，需要再次解析
                    if (dataNode.isTextual()) {
                        String dataString = dataNode.asText();
                        logger.debug("data字段是字符串，内容: {}", dataString);
                        try {
                            JsonNode parsedDataNode = objectMapper.readTree(dataString);
                            logger.debug("解析后的data节点: {}", parsedDataNode);
                            
                            // 检查解析后的data.output
                            if (parsedDataNode.has("output")) {
                                JsonNode outputNode = parsedDataNode.get("output");
                                jobs.addAll(extractJobsFromOutput(outputNode));
                            }
                        } catch (Exception e) {
                            logger.warn("解析data字符串失败: {}", e.getMessage());
                        }
                    } else {
                        // data是对象，直接检查output
                        if (dataNode.has("output")) {
                            JsonNode outputNode = dataNode.get("output");
                            jobs.addAll(extractJobsFromOutput(outputNode));
                        }
                    }
                }
                
                // 如果根节点直接包含output
                if (rootNode.has("output")) {
                    JsonNode outputNode = rootNode.get("output");
                    jobs.addAll(extractJobsFromOutput(outputNode));
                }
                
                // 如果找到了职位，直接返回
                if (!jobs.isEmpty()) {
                    logger.info("从完整JSON响应中解析完成，共找到 {} 个职位", jobs.size());
                    return jobs;
                }
                
            } catch (Exception e) {
                logger.debug("非完整JSON格式，尝试流式解析: {}", e.getMessage());
            }
            
            // 如果不是完整JSON，按行分割响应（流式响应）
            String[] lines = response.split("\n");
            
            for (String line : lines) {
                if (line.trim().isEmpty()) {
                    continue;
                }
                
                String jsonData = line;
                
                // 处理 "data: " 前缀
                if (line.startsWith("data:")) {
                    jsonData = line.substring(5).trim();
                    if (jsonData.equals("[DONE]")) {
                        break;
                    }
                }
                
                try {
                    JsonNode dataNode = objectMapper.readTree(jsonData);
                    logger.debug("解析的JSON节点: {}", dataNode);
                    
                    // 检查多种可能的输出事件类型
                    String eventType = dataNode.path("event").asText();
                    logger.debug("事件类型: {}", eventType);
                    
                    if ("workflow.output".equals(eventType) || "workflow.completed".equals(eventType)) {
                        JsonNode outputNode = dataNode.path("data").path("output");
                        logger.debug("输出节点: {}", outputNode);
                        jobs.addAll(extractJobsFromOutput(outputNode));
                    }
                    
                    // 也检查直接的输出格式
                    if (dataNode.has("output")) {
                        JsonNode outputNode = dataNode.get("output");
                        jobs.addAll(extractJobsFromOutput(outputNode));
                    }
                    
                } catch (Exception e) {
                    logger.warn("解析响应行失败: {}", line, e);
                }
            }
            
            logger.info("解析完成，共找到 {} 个职位", jobs.size());
            return jobs;
            
        } catch (Exception e) {
            logger.error("解析工作流响应失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 从输出节点中提取职位信息
     */
    private List<Map<String, Object>> extractJobsFromOutput(JsonNode outputNode) {
        List<Map<String, Object>> jobs = new ArrayList<>();
        
        try {
            logger.debug("提取职位信息，输出节点: {}", outputNode);
            
            // 如果输出节点本身就是数组，直接处理每个元素
            if (outputNode.isArray()) {
                for (JsonNode item : outputNode) {
                    Map<String, Object> job = parseJobItem(item);
                    if (job != null) {
                        jobs.add(job);
                    }
                }
            } else {
                // 检查是否有嵌套的output数组
                if (outputNode.has("output") && outputNode.get("output").isArray()) {
                    JsonNode outputArray = outputNode.get("output");
                    for (JsonNode item : outputArray) {
                        Map<String, Object> job = parseJobItem(item);
                        if (job != null) {
                            jobs.add(job);
                        }
                    }
                }
                
                // 检查传统的zhiwei格式（向后兼容）
                if (outputNode.has("zhiwei") && outputNode.get("zhiwei").isArray()) {
                    for (JsonNode jobNode : outputNode.get("zhiwei")) {
                        Map<String, Object> job = parseJobNode(jobNode);
                        if (job != null) {
                            jobs.add(job);
                        }
                    }
                }
            }
            
        } catch (Exception e) {
            logger.warn("提取职位信息失败: {}", e.getMessage());
        }
        
        return jobs;
    }
    
    /**
     * 解析新格式的职位项（每个字段包含完整的job信息JSON）
     */
    private Map<String, Object> parseJobItem(JsonNode jobItem) {
        try {
            logger.debug("解析职位项: {}", jobItem);
            
            // 尝试从address字段获取完整的job信息（根据日志分析，address字段包含实际的job数据）
            if (jobItem.has("address") && jobItem.get("address").isTextual()) {
                String addressJson = jobItem.get("address").asText();
                logger.debug("address字段内容: {}", addressJson);
                
                try {
                    JsonNode jobInfoNode = objectMapper.readTree(addressJson);
                    logger.debug("解析后的job信息: {}", jobInfoNode);
                    
                    Map<String, Object> job = new HashMap<>();
                    job.put("name", jobInfoNode.path("name").asText(""));
                    job.put("companyname", jobInfoNode.path("companyName").asText(""));
                    job.put("address", jobInfoNode.path("address").asText(""));
                    job.put("salary", jobInfoNode.path("salary").asText(""));
                    job.put("url", jobInfoNode.path("url").asText(""));
                    job.put("number", jobInfoNode.path("number").asText(""));
                    job.put("property", jobInfoNode.path("property").asText(""));
                    
                    // 只有当职位名称不为空时才返回
                    if (!job.get("name").toString().trim().isEmpty()) {
                        logger.debug("解析到职位: {}", job);
                        return job;
                    }
                } catch (Exception e) {
                    logger.warn("解析address字段中的JSON失败: {}", e.getMessage());
                }
            }
            
            // 如果address字段解析失败，尝试直接从jobItem获取字段
            Map<String, Object> job = new HashMap<>();
            job.put("name", jobItem.path("name").asText(""));
            job.put("companyname", jobItem.path("companyname").asText(""));
            job.put("address", jobItem.path("address").asText(""));
            job.put("salary", jobItem.path("salary").asText(""));
            job.put("url", jobItem.path("url").asText(""));
            job.put("number", jobItem.path("number").asText(""));
            job.put("property", jobItem.path("property").asText(""));
            
            // 只有当职位名称不为空时才返回
            if (!job.get("name").toString().trim().isEmpty()) {
                logger.debug("解析到职位: {}", job);
                return job;
            }
            
            return null;
        } catch (Exception e) {
            logger.warn("解析职位项失败: {}", jobItem, e);
            return null;
        }
    }

    /**
     * 解析单个职位节点（传统格式，向后兼容）
     */
    private Map<String, Object> parseJobNode(JsonNode jobNode) {
        try {
            Map<String, Object> job = new HashMap<>();
            job.put("name", jobNode.path("name").asText(""));
            job.put("companyname", jobNode.path("companyname").asText(""));
            job.put("address", jobNode.path("address").asText(""));
            job.put("salary", jobNode.path("salary").asText(""));
            job.put("url", jobNode.path("url").asText(""));
            job.put("number", jobNode.path("number").asText(""));
            job.put("property", jobNode.path("property").asText(""));
            
            // 只有当职位名称不为空时才返回
            if (!job.get("name").toString().trim().isEmpty()) {
                logger.debug("解析到职位: {}", job);
                return job;
            }
            return null;
        } catch (Exception e) {
            logger.warn("解析职位节点失败: {}", jobNode, e);
            return null;
        }
    }

    /**
     * 职位搜索请求类
     */
    public static class JobSearchRequest {
        private String jobName;        // 职位名称（必填）
        private String city;           // 城市（必填）
        private Integer workExperience; // 工作经验（必填）
        private Integer education;     // 学历（必填）
        private Integer salaryMin;     // 最低薪资（可选）
        private String companyName;    // 公司名称（可选）
        private Integer companyType;   // 公司类型（可选）

        // 构造函数
        public JobSearchRequest() {}

        public JobSearchRequest(String jobName, String city, Integer workExperience, Integer education) {
            this.jobName = jobName;
            this.city = city;
            this.workExperience = workExperience;
            this.education = education;
        }

        // Getters and Setters
        public String getJobName() { return jobName; }
        public void setJobName(String jobName) { this.jobName = jobName; }

        public String getCity() { return city; }
        public void setCity(String city) { this.city = city; }

        public Integer getWorkExperience() { return workExperience; }
        public void setWorkExperience(Integer workExperience) { this.workExperience = workExperience; }

        public Integer getEducation() { return education; }
        public void setEducation(Integer education) { this.education = education; }

        public Integer getSalaryMin() { return salaryMin; }
        public void setSalaryMin(Integer salaryMin) { this.salaryMin = salaryMin; }

        public String getCompanyName() { return companyName; }
        public void setCompanyName(String companyName) { this.companyName = companyName; }

        public Integer getCompanyType() { return companyType; }
        public void setCompanyType(Integer companyType) { this.companyType = companyType; }

        @Override
        public String toString() {
            return "JobSearchRequest{" +
                    "jobName='" + jobName + '\'' +
                    ", city='" + city + '\'' +
                    ", workExperience=" + workExperience +
                    ", education=" + education +
                    ", salaryMin=" + salaryMin +
                    ", companyName='" + companyName + '\'' +
                    ", companyType=" + companyType +
                    '}';
        }
    }

    /**
     * 工作经验枚举
     */
    public enum WorkExperience {
        NO_EXPERIENCE(1, "无经验"),
        LESS_THAN_1_YEAR(2, "1年以下"),
        ONE_TO_THREE_YEARS(3, "1-3年"),
        THREE_TO_FIVE_YEARS(4, "3-5年"),
        FIVE_TO_TEN_YEARS(5, "5-10年"),
        MORE_THAN_TEN_YEARS(6, "10年以上");

        private final int code;
        private final String description;

        WorkExperience(int code, String description) {
            this.code = code;
            this.description = description;
        }

        public int getCode() { return code; }
        public String getDescription() { return description; }
    }

    /**
     * 学历枚举
     */
    public enum Education {
        NO_LIMIT(1, "不限"),
        JUNIOR_HIGH_AND_BELOW(2, "初中及以下"),
        TECHNICAL_SECONDARY(3, "中技"),
        HIGH_SCHOOL(4, "高中"),
        VOCATIONAL_TECHNICAL(5, "中专/中技"),
        COLLEGE(6, "大专"),
        BACHELOR(7, "本科"),
        MASTER(8, "硕士"),
        MBA_EMBA(9, "MBA/EMBA"),
        EMBA(10, "EMBA"),
        DOCTOR(11, "博士"),
        OTHER(12, "其他");

        private final int code;
        private final String description;

        Education(int code, String description) {
            this.code = code;
            this.description = description;
        }

        public int getCode() { return code; }
        public String getDescription() { return description; }
    }

    /**
     * 公司类型枚举
     */
    public enum CompanyType {
        STATE_OWNED(1, "国企"),
        FOREIGN_OWNED(2, "外商独资"),
        REPRESENTATIVE_OFFICE(3, "代表处"),
        JOINT_VENTURE(4, "合资"),
        PRIVATE(5, "民营"),
        GOVERNMENT(6, "国家机关"),
        OTHER(7, "其他"),
        JOINT_STOCK(8, "股份制企业"),
        LISTED_COMPANY(9, "上市公司"),
        INSTITUTION(10, "事业单位"),
        BANK(11, "银行"),
        HOSPITAL(12, "医院"),
        SCHOOL(13, "学校/下级学院"),
        LAW_FIRM(14, "律师事务所"),
        SOCIAL_ORGANIZATION(15, "社会团体"),
        HONG_KONG_MACAO_TAIWAN(16, "港澳台公司");

        private final int code;
        private final String description;

        CompanyType(int code, String description) {
            this.code = code;
            this.description = description;
        }

        public int getCode() { return code; }
        public String getDescription() { return description; }
    }
} 